//
//  MainViewController.swift
//  App_Main
//
//  Created by 蒋晨成 on 2021/12/24.
//

import Adaptor
import App_Common
import Center
import Center_AppInfo
import Foundation
import Route
import UICore
import UIKit

class MainViewController: TabBarViewController {}

// MARK: - Override

extension MainViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
}

private extension MainViewController {
    func setup() {
        Application.add(observable: self)
        OpenAppStoreCenter.register(viewController: self)
        setupTabbarStyle()
        delegate = self
        Adaptor.TabBar.register(tabBarController: self)
        if UserCenter.isLogin {
            UserCenter.getMyProfile(complete: { _ in })
        }
    }

    func setupTabbarStyle() {
        if #available(iOS 15, *) {
            let appearance = UITabBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = .white
            tabBar.standardAppearance = appearance
            tabBar.scrollEdgeAppearance = tabBar.standardAppearance
        }

        tabBar.shadowImage = UIImage(color: MainModular.color(name: "App.Dark5"))
        tabBar.tintColor = MainModular.color(name: "App.Dark1")
        tabBar.isTranslucent = false
        tabBar.barTintColor = MainModular.color(name: "App.Light1")
    }

    func handle(userActivity: NSUserActivity) {
        switch userActivity.activityType {
        case NSUserActivityTypeBrowsingWeb:
            guard let webpageURL = userActivity.webpageURL else { return }
            switch UniversalLinksCenter.handle(url: webpageURL.absoluteString) {
            case .some(let pattern):
                guard let url = URL(string: "\(AppInfoCenter.appScheme)://\(pattern)") else { return }
                Router.open(url: url)
            case .none:
                Router.open(url: webpageURL)
            }
        default:
            logger.warning("unhandled \(userActivity)")
        }
    }
}

// MARK: - ApplicationObservable

extension MainViewController: ApplicationObservable {
    func applicationDidBecomeActive() {}

    func scene(_: UIScene, continue userActivity: NSUserActivity) {
        handle(userActivity: userActivity)
    }

    func scene(_: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        guard let url = URLContexts.first?.url else { return }
        Router.open(url: url)
    }
}

// MARK: - UITabBarControllerDelegate

extension MainViewController: UITabBarControllerDelegate {
    func tabBarController(_: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        guard let index = viewControllers?.firstIndex(of: viewController) else { return false }
        logger.debug("\(index)")
        return true
    }
}
